package com.zide.ams.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.zide.ams.domain.po.AmsArticle;
import com.zide.ams.domain.po.AmsCategory;
import com.zide.ams.domain.po.AmsCollect;
import com.zide.ams.domain.po.AmsLike;
import com.zide.ams.domain.vo.result.AmsArticleResultVO;
import com.zide.ams.domain.vo.save.AmsArticleSaveVO;
import com.zide.ams.domain.vo.search.AmsArticleSearchVO;
import com.zide.ams.mapper.AmsArticleMapper;
import com.zide.ams.mapper.AmsCategoryMapper;
import com.zide.ams.mapper.AmsCollectMapper;
import com.zide.ams.mapper.AmsLikeMapper;
import com.zide.ams.service.IAmsArticleService;
import com.zide.common.constant.HttpStatus;
import com.zide.common.core.domain.PageResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.zide.common.core.domain.entity.SysUser;
import com.zide.common.core.domain.entity.UmsMember;
import com.zide.common.core.vo.CommonParamIdVO;
import com.zide.common.exception.ServiceException;
import com.zide.common.utils.SecurityUtils;
import com.zide.framework.web.mapper.SysUserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 博客文章Service业务层处理
 * 
 * @author zide
 * @date 2024-04-29
 */
@Slf4j
@Service
public class AmsArticleServiceImpl implements IAmsArticleService {
    @Resource
    private AmsArticleMapper amsArticleMapper;
    @Resource
    private AmsCategoryMapper amsCategoryMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private AmsCollectMapper amsCollectMapper;
    @Resource
    private AmsLikeMapper amsLikeMapper;

    /**
     * 查询博客文章列表
     */
    @Override
    public PageResult<AmsArticleResultVO> searchAmsArticlePageList(AmsArticleSearchVO searchVO) {
        MPJLambdaWrapper<AmsArticle> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(AmsArticle.class)
                .selectAs(UmsMember::getNickname,"authorName")
                .selectAs(UmsMember::getAvatar,"authorAvatar")
                .leftJoin(UmsMember.class,UmsMember::getId,AmsArticle::getUserId);

        if(ObjectUtil.isNotNull(searchVO.getCategoryId())) {
            Long categoryId = searchVO.getCategoryId();
            AmsCategory amsCategory = amsCategoryMapper.selectById(categoryId);
            if(ObjectUtil.isNotNull(amsCategory)) {
                Long parentId = amsCategory.getParentId();
                if(parentId == 0) {
                    List<AmsCategory> amsCategories = amsCategoryMapper.selectList(new LambdaUpdateWrapper<AmsCategory>().eq(AmsCategory::getParentId, amsCategory.getId()));
                    if(CollectionUtil.isNotEmpty(amsCategories)) {
                        wrapper.in(AmsArticle::getCategoryId,amsCategories.stream().map(AmsCategory::getId).collect(Collectors.toList()));
                    }else {
                        wrapper.eq(AmsArticle::getCategoryId,searchVO.getCategoryId());
                    }
                }else {
                    wrapper.eq(AmsArticle::getCategoryId,searchVO.getCategoryId());
                }
            }
        }
        if(StrUtil.isNotEmpty(searchVO.getTitle())) {
            wrapper.eq(AmsArticle::getTitle,searchVO.getTitle());
        }
        wrapper.orderByDesc(AmsArticle::getCreateTime);
        PageResult<AmsArticleResultVO> result = amsArticleMapper.selectJoinPage(searchVO, AmsArticleResultVO.class,wrapper);
        return result;
    }

    /**
     * 查询热门文章
     * @return
     */
    @Override
    public List<AmsArticleResultVO> searchHotList() {
        LambdaQueryWrapper<AmsArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(AmsArticle::getReadVolume);
        wrapper.last("limit 8");
        List<AmsArticle> amsArticleList = amsArticleMapper.selectList(wrapper);
        return BeanUtil.copyToList(amsArticleList,AmsArticleResultVO.class);
    }

    /**
     * 阅读文章
     * @param articleId
     * @return
     */
    @Override
    public AmsArticleResultVO readArticle(Long articleId) {
        AmsArticle dbInfo = amsArticleMapper.selectById(articleId);
        AmsArticleResultVO result = BeanUtil.copyProperties(dbInfo,AmsArticleResultVO.class);
        String tag = result.getTag();
        if(StrUtil.isNotEmpty(tag)) {
            result.setCheckedTagList(StrUtil.split(tag,','));
        }
        // 查询作者信息
        Long userId = result.getUserId();
        SysUser sysUser = sysUserMapper.selectById(userId);
        if(ObjectUtil.isNotNull(sysUser)) {
            String nickname = sysUser.getNickname();
            result.setAuthorName(nickname);
            result.setAuthorAvatar(sysUser.getAvatar());
        }
        // 修改阅读次数
        dbInfo.setReadVolume(dbInfo.getReadVolume() + 1);
        amsArticleMapper.updateById(dbInfo);
        // 判断是否收藏，点赞
        long loginUserId = SecurityUtils.getMemberUserId();
        if(loginUserId != 0) {
            Long collectStatus = amsCollectMapper.selectCount(new LambdaQueryWrapper<AmsCollect>().eq(AmsCollect::getArticleId, articleId).eq(AmsCollect::getUserId, loginUserId));

            Long likeStatus = amsLikeMapper.selectCount(new LambdaQueryWrapper<AmsLike>().eq(AmsLike::getArticleId, articleId).eq(AmsLike::getUserId, loginUserId));
            if(collectStatus > 0) {
                result.setCollectStatus(1);
            }
            if(likeStatus > 0) {
                result.setLikeStatus(1);
            }
        }

        return result;
    }

    /**
     * 查询博客文章详情
     */
    @Override
    public AmsArticleResultVO selectAmsArticleById(Long id) {
        AmsArticle dbInfo = amsArticleMapper.selectById(id);
        AmsArticleResultVO result = BeanUtil.copyProperties(dbInfo,AmsArticleResultVO.class);
        return result;
    }

    /**
     * 新增博客文章
     */
    @Override
    public int saveAmsArticle(AmsArticleSaveVO saveVO) {
        AmsArticle insertBean = BeanUtil.copyProperties(saveVO,AmsArticle.class);
        List<String> checkedTagList = saveVO.getCheckedTagList();
        if(CollectionUtil.isNotEmpty(checkedTagList)) {
            insertBean.setTag(StrUtil.join(",",checkedTagList));
        }
        LocalDateTime currentTime = LocalDateTime.now();
        insertBean.setCreateTime(currentTime);
        insertBean.setUpdateTime(currentTime);
        Long userId = SecurityUtils.getMemberUserId();
        if(ObjectUtil.isNull(userId)) {
            throw new ServiceException(HttpStatus.FORBIDDEN,"");
        }
        insertBean.setUserId(userId);
        return amsArticleMapper.insert(insertBean);
    }

    /**
     * 修改博客文章
     */
    @Override
    public int updateAmsArticle(AmsArticleSaveVO saveVO) {
        AmsArticle updateBean = BeanUtil.copyProperties(saveVO,AmsArticle.class);
        List<String> checkedTagList = saveVO.getCheckedTagList();
        if(CollectionUtil.isNotEmpty(checkedTagList)) {
            updateBean.setTag(StrUtil.join(",",checkedTagList));
        }
        updateBean.setUpdateTime(LocalDateTime.now());
        Long userId = SecurityUtils.getMemberUserId();
        if(ObjectUtil.isNull(userId)) {
            throw new ServiceException(HttpStatus.FORBIDDEN,"");
        }
        updateBean.setUserId(userId);
        return amsArticleMapper.updateById(updateBean);
    }

    /**
     * 批量删除博客文章
     */
    @Override
    public int removeAmsArticleByIds(CommonParamIdVO idVO) {
        if(ArrayUtil.isNotEmpty(idVO.getIds())) {
            return amsArticleMapper.deleteBatchIds(Arrays.asList(idVO.getIds()));
        }else {
            return amsArticleMapper.deleteById(idVO.getId());
        }

    }
}
